﻿using BCCommon;
using BCData.TMS.Packing.PackingCategoryConfig;
using BCData.TMS.Packing.PackingConfig;
using BCDto.Sim.Admin.Admin;
using BCDto.TMS.Packing.PackingCategoryConfig;
using BCEntity.Common.EntityNameConst;
using BCEntity.TMS.Packing.PackingCategoryConfig;
using BCService.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BCService.TMS.Packing.PackingCategoryConfig
{
    public class PackingCategoryConfigService : IPackingCategoryConfigService
    {
        private readonly IPackingCategoryConfigData packingCategoryConfigData;
        private readonly IRedisService redisService;
        private readonly IPackingConfigData packingConfigData;
        private readonly IPackingConfigOverwriteData packingConfigOverwriteData;
        private readonly string key = string.Format("{0}", EntityNameConst.PackingCategoryConfigEntity);

        public PackingCategoryConfigService(IPackingCategoryConfigData packingCategoryConfigData,
            IRedisService redisService,
            IPackingConfigData packingConfigData,
            IPackingConfigOverwriteData packingConfigOverwriteData)
        {
            this.packingCategoryConfigData = packingCategoryConfigData;
            this.redisService = redisService;
            this.packingConfigData = packingConfigData;
            this.packingConfigOverwriteData = packingConfigOverwriteData;
        }

        public PackingCategoryConfigDto Create(AdminDto admin, PackingCategoryConfigRequestDto requestDto)
        {
            if (admin.CompanyId != 1)
            {
                throw new ArgumentException("您不是总公司员工，暂无权限添加");
            }
            if (string.IsNullOrWhiteSpace(requestDto.PackingCategory))
            {
                throw new ArgumentException("包装材料分类不允许为空");
            } 
            if (requestDto.PackingCategory.Trim().Length > 30)
            {
                throw new ArgumentException("包装材料分类字段长度不能超出30个字");
            }
            var result = this.packingCategoryConfigData.GetByPackingCategory(requestDto.PackingCategory.Trim()).Result;
            if (result != null)
            {
                throw new ArgumentException("此材料分类已存在，不需重复添加");
            }
            result = this.packingCategoryConfigData.Insert(new PackingCategoryConfigEntity()
            {
                PackingCategory = requestDto.PackingCategory.Trim(),
                CreateAdminId = admin.AdminId,
                CreateAdminName = admin.FullName,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                EditAdminId = admin.AdminId,
                EditAdminName = admin.FullName
            }).GetAwaiter().GetResult();
            this.redisService.DeleteMultipleKey(key, false);
            return result.As<PackingCategoryConfigDto>();
        }

        public void Delete(AdminDto admin, int packingCategoryConfigId)
        {
            if (admin.CompanyId != 1)
            {
                throw new ArgumentException("您不是总公司员工，暂无权限修改");
            }
            var result = this.packingCategoryConfigData.GetEntity(packingCategoryConfigId).Result;
            if (result == null)
            {
                throw new ArgumentException("此包装材料分类配置信息不存在");
            }
            var packingConfig = this.packingConfigData.GetEntityByCategoryConfigId(packingCategoryConfigId).Result;
            if (packingConfig != null)
            {
                throw new ArgumentException("此包装材料分类配置已在包装材料配置使用，不允许删除");
            }
            var packingConfigOverwrite = this.packingConfigOverwriteData.GetEntityByCategoryConfigId(packingCategoryConfigId).Result;
            if (packingConfigOverwrite != null)
            {
                throw new ArgumentException("此包装材料分类配置已在包装材料配置重写记录使用，不允许删除");
            }
            this.packingCategoryConfigData.Delete(packingCategoryConfigId).GetAwaiter().GetResult();
            string cacheKey = this.redisService.GetKey(key, packingCategoryConfigId);
            this.redisService.DeleteAsync(cacheKey);
        }

        public IEnumerable<PackingCategoryConfigDto> List(AdminDto admin)
        {
            var result = this.redisService.TryGet(key, () =>
            {
                var data = this.packingCategoryConfigData.GetList().Result;
                return data;
            }, TimeSpan.FromDays(1));
            return result.As<IEnumerable<PackingCategoryConfigDto>>();
        }

        public PageableList<PackingCategoryConfigDto> Query(AdminDto admin, string packingCategory, DateTime? createStartDate, DateTime? createEndDate, int pageIndex, int pageSize)
        {
            string cacheKey = this.redisService.GetKey(key, packingCategory, createStartDate, createEndDate, pageIndex, pageSize);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var (data, dataCount) = this.packingCategoryConfigData.Query(packingCategory, createStartDate, createEndDate, pageIndex, pageSize).Result;
                return new PageableList<PackingCategoryConfigDto>()
                {
                    Count = dataCount,
                    Items = data.As<List<PackingCategoryConfigDto>>(),
                    PageIndex = pageIndex,
                    PageSize = pageSize
                };
            }, TimeSpan.FromDays(365));

            return result;
        }

        public PackingCategoryConfigDto Update(AdminDto admin, int packingCategoryConfigId, PackingCategoryConfigRequestDto requestDto)
        {
            if (admin.CompanyId != 1)
            {
                throw new ArgumentException("您不是总公司员工，暂无权限修改");
            }
            if (string.IsNullOrWhiteSpace(requestDto.PackingCategory))
            {
                throw new ArgumentException("包装材料分类不允许为空");
            }
            if (requestDto.PackingCategory.Trim().Length > 30)
            {
                throw new ArgumentException("包装材料分类字段长度不能超出30个字");
            }
            var configList = this.packingCategoryConfigData.GetList().Result;
            if (!configList.Any(p => p.PackingCategoryConfigId == packingCategoryConfigId))
            {
                throw new ArgumentException("此包装材料分类配置信息不存在");
            }
            if (configList.Any(p => p.PackingCategoryConfigId != packingCategoryConfigId && p.PackingCategory == requestDto.PackingCategory.Trim()))
            {
                throw new ArgumentException("此材料分类已存在，请更换其他名称");
            }
            var result = configList.FirstOrDefault(p => p.PackingCategoryConfigId == packingCategoryConfigId);
            result.PackingCategory = requestDto.PackingCategory.Trim();
            result.UpdateTime = DateTime.Now;
            result.EditAdminId = admin.AdminId;
            result.EditAdminName = admin.FullName;
            result = this.packingCategoryConfigData.Update(result).GetAwaiter().GetResult();
            string cacheKey = this.redisService.GetKey(key, packingCategoryConfigId);
            this.redisService.DeleteAsync(cacheKey);
            return result.As<PackingCategoryConfigDto>();
        }
    }
}
